package com.xinxing.city.recovery.camea;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    /**
     * 判断内存卡是否存在
     * @return
     */
    public static boolean SDCardIsAvailable() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }
    /**
     * 获取图片存储路径
     * @return
     */
    public static File getFilePath() {
        if (!SDCardIsAvailable()) {
            throw new RuntimeException("the sdcard is error,please check sdcard and try again");
        }
        //get the mobile Pictures directory
        File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        //get the current time
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        Log.i("picPath", picDir.getPath() + File.separator + timeStamp);
        return new File(picDir.getPath() + File.separator + "IMAGE_" + timeStamp + ".jpg");
    }
    /**
     * 将数据一.jpg格式保存到指定的路径中
     * @param data
     * @param file
     */
    public static void saveData2Pic(byte data[], File file) {
        if (null == file || data == null) {
            Log.d("sava picture is failed", "FileUtil.class--saveData2Pic");
            return;
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(data);
            fos.flush();
            Log.i("save pic is successful", file.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null == fos) {
                return;
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
